package com.dreamwhale.machinery.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dreamwhale.machinery.config.DataResult;
import com.dreamwhale.machinery.config.HttpRequest;
import com.dreamwhale.machinery.config.StringUtils;
import com.dreamwhale.machinery.config.WXBizDataCrypt;
import com.dreamwhale.machinery.dao.VipUserInfoMapper;
import com.dreamwhale.machinery.entity.VipUserInfo;
import com.dreamwhale.machinery.user.entity.YxUser;
import com.dreamwhale.machinery.user.mapper.YxUserMapper;
import com.dreamwhale.machinery.user.service.YxUserService;
import com.dreamwhale.machinery.utils.JwtUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserLoginController {


    @Resource
    private YxUserMapper yxUserMapper;
    @Resource
    private YxUserService yxUserService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private VipUserInfoMapper vipUserInfoMapper;

    /**
     * 登陆
     *
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getWeOpenIDCodes", method = RequestMethod.GET)
    public DataResult getWeOpenIDCodes(String code) {
        System.out.println("=====================" + code);
        try {
            System.out.println("查询用户的OpenID");
            Map map = new HashMap();
            //登录凭证不能为空
            if (code == null || code.length() == 0) {
                map.put("status", 0);
                map.put("msg", "code 不能为空");
                return DataResult.build(300, "code 不能为空");
            }

            //小程序唯一标识   (在微信小程序管理后台获取)
//            String wxspAppid = "wxa01518371f187b24";
            String wxspAppid = "wxbc645cafc9875782";
            //小程序的 app secret (在微信小程序管理后台获取)
//            String wxspSecret = "975f6d74c4feb75c27b066cdd5f9dd68";
            String wxspSecret = "a643b4a2ca606e1f4df1f883899d4ddc";
            //授权（必填）
            String grant_type = "authorization_code";


            //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
            //请求参数
            String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
            //发送请求
            String sr = HttpRequest.sendWeOpenIdGet("https://api.weixin.qq.com/sns/jscode2session", params);
            System.out.println("================请求地址" + sr);
            //解析相应内容（转换成json对象）
            JSONObject json = JSONObject.fromObject(sr);
            System.out.println("=============" + json);
            //获取会话密钥（session_key）
            String session_key = json.get("session_key").toString();
            //用户的唯一标识（openid）
            String openid = (String) json.get("openid");
            System.out.println("================openid" + openid);

            Map<String, Object> maps = new HashMap<>();
            maps.put("openid", openid);
            maps.put("session_key", session_key);
            return DataResult.ok(maps);

            //  ------用户的注册的功能结束----------------------------
        } catch (Exception e) {
            e.printStackTrace();
            return DataResult.build(300, "登录失败");
        }
    }


    /**
     * 小程序授权获取手机号
     *
     * @param encryptedData
     * @param iv
     * @param session_key   获取openid的时候进行返回的
     *                      https://blog.csdn.net/qq_44614878/article/details/103391335
     * @return
     */
    @RequestMapping(value = "/getPhoneNumber")
    public DataResult getPhoneNumber(String encryptedData, String iv, String code) {

        System.out.println("查询用户的OpenID");
        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return DataResult.build(300, "code 不能为空");
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
//            String wxspAppid = "wxa01518371f187b24";
        String wxspAppid = "wxbc645cafc9875782";
        //小程序的 app secret (在微信小程序管理后台获取)
//            String wxspSecret = "975f6d74c4feb75c27b066cdd5f9dd68";
        String wxspSecret = "a643b4a2ca606e1f4df1f883899d4ddc";
        //授权（必填）
        String grant_type = "authorization_code";

        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendWeOpenIdGet("https://api.weixin.qq.com/sns/jscode2session", params);
        System.out.println("================请求地址" + sr);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.fromObject(sr);
        System.out.println("=============" + json);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        System.out.println("================openid" + openid);

        //获取手机号
        String result = WXBizDataCrypt.decrypt1(encryptedData, session_key, iv);
        JSONObject jsons = JSONObject.fromObject(result);
        HashMap<String, Object> resultMap = new HashMap<>();
        if (!StringUtils.isEmpty(result) && result.length() > 0) {
            //电话号码
            String purePhoneNumber = jsons.get("purePhoneNumber").toString();
            System.out.println(purePhoneNumber);
            QueryWrapper<YxUser> qw = new QueryWrapper<YxUser>();
            qw.eq("status", 1).eq("phone", purePhoneNumber);
            List<YxUser> list = yxUserMapper.selectList(qw);
            if (list != null && list.size() > 0) {
                YxUser yxUser = list.get(0);
                yxUser.setMark(session_key);
                List<VipUserInfo> vipUserInfos = vipUserInfoMapper.selectList(new QueryWrapper<VipUserInfo>().eq("uid", yxUser.getUid()).orderByDesc("expiration_time"));
                if (!CollectionUtils.isEmpty(vipUserInfos)) {
                    VipUserInfo vipUserInfo = vipUserInfos.get(0);
                    LocalDateTime expirationTime = vipUserInfo.getExpirationTime();
                    resultMap.put("vipStatus", expirationTime.compareTo(LocalDateTime.now()) > 0);
                    resultMap.put("vipValidTime", expirationTime);
                }
                //已存在此用户
                String jwtToken = jwtUtils.createJwtToken(8640000L, yxUser.getUid().longValue());
                resultMap.put("token", jwtToken);
                resultMap.put("yxUser", yxUser);
                return DataResult.ok(resultMap);
            } else {
                //没有没有用户，创建新用户
                YxUser yxUser = new YxUser();
                yxUser.setOpenId(openid);
                yxUser.setAccount(purePhoneNumber);
                yxUser.setPhone(purePhoneNumber);
                yxUser.setAddTime(LocalDateTime.now());
                String password = "123456";
                String s = DigestUtils.md5DigestAsHex(password.getBytes());
                yxUser.setPwd(s);
                yxUserMapper.insert(yxUser);
                //把session_key传给前端，在解密手机号的时候再给我
                yxUser.setMark(session_key);
                String jwtToken = jwtUtils.createJwtToken(8640000L, yxUser.getUid().longValue());
                resultMap.put("token", jwtToken);
                resultMap.put("yxUser", yxUser);
                resultMap.put("vipStatus", false);
                resultMap.put("vipValidTime", null);
                return DataResult.ok(resultMap);
            }

        }
        return DataResult.ok(1);
    }


    /**
     * 保存信息用
     *
     * @param yxUser
     * @return
     */
    @RequestMapping("/updateInfoUserLogin")
    public DataResult updateInfoUserLogin(YxUser yxUser) {
        yxUser.setNickname(Base64.getEncoder().encodeToString(yxUser.getNickname().getBytes()));
        int num = yxUserMapper.updateById(yxUser);
        if (num > 0) {
            return DataResult.ok();
        } else {
            return DataResult.build(300, "保存失败！");
        }

    }

}




